import EchartsComponent, { MyChartOption } from '@/components/EchartsComponent';
import { getEmptyOptions } from '@/dictionary';
import { timeToDecimal } from '@/pages/OverView/utils/tools';
import { statisticWorkStatusControllerGetDateWorkStatus } from '@/services/ess/statisticWorkstatus';
import { fetchDictInfo } from '@/utils';
import { useIntl } from '@umijs/max';
import { Spin } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import ChartForm from './ChartForm';
import Styles from './Common.less';
import { SubmitType } from './Type';
//  工况对应颜色的映射关系
const colorMap = new Map<number | string, string>([
  [0, '#FFD50C'], //静置
  [1, '#56D433'], //充电
  [2, '#1A6CFE'], // 放电
  [20, '#8662F1'], //调试
  [50, '#FF5353'], // 故障
]);

function fixFloatingPoint(num: number): number {
  return parseFloat(num.toFixed(2));
}

/**
 *  获得两段时间的分钟
 *  @param  startTime
 *  @param  endTime
 */
// const getMinute = (startTime: string, endTime: string) => {
//   const startDate = new Date(startTime);
//   const endDate = new Date(endTime);
//   const diff = endDate - startDate;
//   return (diff / 1000 / 60).toFixed(1);
// };
const DayChart: React.FC = () => {
  const intl = useIntl();
  const [chartLoading, setChartLoading] = useState(false);
  //  定义状态变量和ref
  const [option, setOptions] = useState<MyChartOption>();
  const chartRef = useRef(null);
  //  表单提交函数
  const handleSubmit = (value: SubmitType) => {
    if (option) {
      setChartLoading(true);
    }
    //  根据表单的值构造获取工况数据的参数
    const params = {
      date: dayjs(value.date).format('YYYY-MM-DD'),
      dataType: value.areaIdList ? '3' : value.staticDimension === 'station' ? '1' : '2',
      code: value.areaIdList ? '' : value.code,
      areaIdList: value.areaIdList,
    };
    //  根据工况编号获取工况字典信息
    fetchDictInfo(100036, true).then((dictRes) => {
      //  根据参数获取工况数据
      statisticWorkStatusControllerGetDateWorkStatus(params)
        .then((res) => {
          //  如果请求成功且有数据
          if (res.success && res.data && res.data.length > 0) {
            console.log(res, '请求成功数据范德萨范德萨范德萨发佛挡杀佛');
            //  数据处理
            const seriesData = res.data.map((item) => {
              if (item.id) {
                return {
                  name: dictRes.filter((dictItem) => dictItem.value === item.workState)[0]?.label,
                  stack: intl.formatMessage({ id: 'statistics.work.work' }),
                  data: [
                    {
                      startTime: item.startTime?.slice(10, 19),
                      endTime: item.endTime?.slice(10, 19),
                      minute: item.durationTime,
                      maxCurrentTime: item?.largeCurrentTime,
                      minCurrentTime: item?.lowCurrentTime,
                      value: fixFloatingPoint(
                        timeToDecimal(item.endTime?.slice(10, 19) as string) -
                          timeToDecimal(item.startTime?.slice(10, 19) as string),
                      ),
                    },
                  ],
                  itemStyle: {
                    color: colorMap.get(item.workState),
                    opacity: 1,
                  },
                  type: 'bar',
                };
              } else {
                return {
                  name: '',
                  stack: intl.formatMessage({ id: 'statistics.work.work' }),
                  data: [
                    {
                      startTime: item.startTime?.slice(10, 19),
                      endTime: item.endTime?.slice(10, 19),
                      minute: item.durationTime,
                      value: fixFloatingPoint(
                        timeToDecimal(item.endTime?.slice(10, 19) as string) -
                          timeToDecimal(item.startTime?.slice(10, 19) as string),
                      ),
                    },
                  ],
                  itemStyle: {
                    color: colorMap.get(item.workState),
                    opacity: 0,
                  },
                  type: 'bar',
                };
              }
            });
            const chartOptions: MyChartOption = {
              //  图表工具提示
              tooltip: {
                trigger: 'item',
                formatter: function (params: any) {
                  return `${dayjs(value.date).format('YYYY-MM-DD')}<br/>${params.data.startTime}-${
                    params.data.endTime
                  }
                    <br/>
                    ${intl.formatMessage({ id: 'statistics.work.work' })}：${
                    params.seriesName
                  }<br/>${intl.formatMessage({
                    id: 'statistics.work.workTime',
                  })}(${intl.formatMessage({ id: 'statistics.common.mins' })})：${
                    params.data.minute || '-'
                  }<br/>${intl.formatMessage({
                    id: 'statistics.analyze.maxCurrentTimeNounit',
                  })}:${params.data?.maxCurrentTime ?? '-'}<br/>${intl.formatMessage({
                    id: 'statistics.analyze.minCurrentTimeNounit',
                  })}:${params.data?.minCurrentTime ?? '-'}`;
                },
              },
              //  图表视图显示
              grid: {
                left: '0%',
                right: '5%',
                bottom: '0%',
                top: '80%',
                containLabel: true,
              },
              legend: {
                right: 0,
                icon: 'rect',
              },
              xAxis: {
                type: 'value',
                gridIndex: 0,
                min: 0,
                max: 24,
                // boundaryGap: [0, 0.1],
                interval: 2, // 每隔 2 个单位显示一个刻度
                show: true, // 显示 X 轴
                axisLine: {
                  show: false, // 不显示 X 轴的主线
                },
                axisTick: {
                  show: false, // 显示刻度
                  interval: 0, // 保持每个刻度都显示
                },
                axisLabel: {
                  show: true, // 显示标签
                },
                splitLine: {
                  show: false,
                },
              },
              yAxis: {
                type: 'category',
                show: false,
                gridIndex: 0,
                data: ['状态'],
              },
              series: seriesData,
            };
            //  清除图表数据并设置新的数据
            chartRef?.current?.instance().clear();
            setOptions(chartOptions);
            setChartLoading(false);
            chartRef?.current?.instance().off('legendselectchanged');
            chartRef?.current?.instance().on('legendselectchanged', function (params) {
              function getOpacity(name: string, currentName: string, opacity: number): number {
                if (opacity === 0) {
                  return name === currentName ? 1 : 0;
                } else {
                  return name === currentName ? 0 : 1;
                }
              }

              const series = JSON.parse(
                JSON.stringify(chartRef?.current?.instance()?.getOption()?.series),
              );
              const getData = () => {
                return series.map((item) => {
                  return {
                    ...item,
                    itemStyle: {
                      color: item.itemStyle.color,
                      opacity: getOpacity(item.name, params.name, item.itemStyle.opacity),
                    },
                  };
                });
              };
              const selectedOBJ = Object.keys(params.selected).reduce((acc, key) => {
                acc[key] = true;
                return acc;
              }, params.selected);
              chartRef?.current?.instance().setOption({
                series: getData(),
                legend: {
                  selected: selectedOBJ,
                },
              });
            });
          } else {
            setChartLoading(false);
            if (
              chartRef?.current?.instance() &&
              chartRef?.current?.instance().getOption()?.series.length !== 0
            ) {
              chartRef?.current?.instance().clear();
            }
            setOptions(getEmptyOptions());

            //  chartRef?.current?.instance().setOption(EMPTY_OPTIONS);
          }
        })
        .catch(() => {
          setChartLoading(false);
        });
    });
  };
  useEffect(() => {
    setChartLoading(true);
  }, []);
  return (
    //  返回Chart内容
    <div className={Styles.chartContent}>
      <ChartForm dateType={'date'} submitForm={handleSubmit} />
      <Spin spinning={chartLoading}>
        <EchartsComponent
          ref={chartRef}
          option={option}
          width={'auto'}
          height={500}
        ></EchartsComponent>
      </Spin>
    </div>
  );
};

export default DayChart;
